package com.sh.common.error;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 
 * NOTE: 异常处理
 *
 * @author: king
 * @date: 2019年3月31日
 *
 */
@RestControllerAdvice
@ControllerAdvice
public class GobalExceptionHandler extends ResponseEntityExceptionHandler {
	
	private static final Logger log = Logger.getLogger(GobalExceptionHandler.class);

	/**
	 * 
	 * @description: 自定义异常处理
	 * 
	 * @author: king
	 * @date: 2019年1月29日
	 *
	 * @param request
	 * @param response
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = SystemException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ErrorInfo exceptionHandler(HttpServletRequest request, HttpServletResponse response, SystemException e) {
		log.info("GobalExceptionHandler - Exception: " + e.getMessage() + ", URL: " + request.getRequestURL().toString());
		ErrorInfo error = new ErrorInfo();
		error.setCode(e.getCode());
		error.setMessage(e.getMessage());
		error.setUrl(request.getRequestURL().toString());
		
		return error;
	}
	
	/**
	 * 
	 * @description: 未知异常处理
	 * 
	 * @author: king
	 * @date: 2019年1月29日
	 *
	 * @param request
	 * @param response
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ErrorInfo exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		log.error("GobalExceptionHandler - Exception: " + e.getMessage() + ", URL: " + request.getRequestURL().toString());
		log.error(getExceptionMessage(e));
		ErrorInfo error = new ErrorInfo();
		error.setCode("909");
		error.setMessage("系統異常");
		error.setUrl(request.getRequestURL().toString());
		
		return error;
	}
	
	public String getExceptionMessage(Exception ex) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		return sw.toString();
	}
}
